import { Message, requestLogger } from '@/libs/index';
import { AxiosResponse } from 'axios';
// import { NetCode, BusinessCode } from '../axios/code';
import { ResponseDataType } from './types/index';

/**
 * 设置响应拦截器
 * @param response axios响应内容
 * @returns
 */
// 出现兼容性问题，此处使用async+await，ios无法进入resolve状态，估计是axios问题？
export const setResponseConfig = (response: AxiosResponse<ResponseDataType>): Promise<ResponseDataType> => {
  // 控制台输出日志
  requestLogger({
    url: `${response.config.baseURL}${response.config.url}`,
    headers: response.config.headers,
    method: response.config.method,
    params: response.config.params,
    data: response.config.data,
    response: response,
    request: response.config
  });

  if (!response?.data) {
    throw new Error('response.data is null/undefined!');
  }
  const data = response?.data;
  if (data?.code !== 200) {
    // 这个部分用于处理业务状态码非200状态下的错误处理
    // const errMessage = BusinessCode.getBusinessErroMessage(code);
    return Message.error(data?.msg || data?.message).then(() => {
      // BusinessCode.dealBusinessError[data?.code] && BusinessCode.dealBusinessError[data?.code](data?.msg || data?.msg);
      return Promise.reject(data);
    });
  }
  return Promise.resolve(data);
};

export const setResponseError = (error: any) => {
  // const errMessage = NetCode.getErroMessage(error && error.response && error.response.status);
  return Message.error('出现错误').then(() => {
    return Promise.reject({
      code: (error && error.response && error.response.status) || 500,
      msg: '出现错误'
    });
  });
};
